import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: GlobalKeyDemo(),
    );
  }
}

class GlobalKeyDemo extends StatefulWidget {
  const GlobalKeyDemo({super.key});

  @override
  State<GlobalKeyDemo> createState() => _GlobalKeyDemoState();
}

class _GlobalKeyDemoState extends State<GlobalKeyDemo> {
  // 创建一个全局 key
  final GlobalKey<_CounterWidgetState> _counterKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("GlobalKey 示例")),
      body: Center(
        child: CounterWidget(key: _counterKey), // 使用 key
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // 通过 key 获取 CounterWidget 的 state 并调用方法
          _counterKey.currentState?.increment();

          print(_counterKey.currentContext); // 打印这个容器的上下文
          final RenderBox box = _counterKey.currentContext!.findRenderObject() as RenderBox;
          final size = box.size;
          final position = box.localToGlobal(Offset.zero);
          // _counterKey.currentState?.validate(); // 校验表单
        },
        child: const Icon(Icons.add),
      ),
    );
  }
}

class CounterWidget extends StatefulWidget {
  const CounterWidget({super.key});

  @override
  State<CounterWidget> createState() => _CounterWidgetState();
}

class _CounterWidgetState extends State<CounterWidget> {
  int _count = 0;

  void increment() {
    setState(() {
      _count++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Text("计数：$_count", style: const TextStyle(fontSize: 24));
  }
}
